<?php

/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class Controller extends CController {

    /**
     * @var string 
     */
    public $layout;

    /**
     * @var array 
     */
    public $breadcrumbs;

    /**
     * @var array
     */
    public $nav;

    /**
     * 
     * @var array
     */
    public $languages;

    /**
     * 
     * @var array
     */
    public $relatedNews;

    /**
     * 
     */
    public function __construct($id, $module = NULL) {
        parent::__construct($id, $module);

        $this->layout = '//layouts/column1';
        $this->breadcrumbs = array();

        $this->languages = array('default' => 'en',
            'supported' => array('vn', 'en'));

        $this->initLanguage();
        $this->relatedNews = array();
    }

    /**
     * 
     */
    public function initLanguage() {
        $ip = Yii::app()->request->userHostAddress;
        if ($this->getCountryCode($ip) === 'VN') {
            Yii::app()->language = 'vn';
        } else {
            Yii::app()->language = $this->languages['default'];
        }
    }

    /*
     * 
     */

    private function getCountryCode($ip) {
        $countryCode = 'VN';
        try {
            $location = Yii::app()->geoip->lookupLocation($ip);
            if ($location === null) {
                $countryCode = 'US';
            } else {
                $countryCode = $location->countryCode;
            }
            if (empty($countryCode)) {
                $countryCode = 'US';
            }
        } catch (Exception $ex) {
            $countryCode = 'US';
        }
        return $countryCode;
    }

    public function getCurrentLanguage() {
        $language = Yii::app()->language;
        if (!isset($language)) {
            $language = 'en';
        };
        return $language;
    }

}